//
//  ST_BTPlayerViewController.swift
//  DrinkTogether
//
//  Created by DouLei on 2018/6/6.
//  Copyright © 2018 DouLei. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import Photos

enum ST_DTPlayType {
    case localUrl
    case networkUrl
    case asset
}

class ST_BTPlayerViewController: UIViewController {

//        MARK:- public properties
    var type = ST_DTPlayType.localUrl
    
    var videoUrl = ""
    
    var asset:PHAsset?
    
    typealias click_closure = () ->()
    var show_delete_action:Bool = false
    var delete_block:click_closure?
    
//        MARK:- private properties
    private var url:URL!{
        didSet{
            self.d_tinit_player()
        }
    }
    
    private var player_status_context = 0
    
    private var player:AVPlayer?
    
    private var playLayer:AVPlayerLayer?
    
    private let playView = UIView()
    // 0 :播放中，1:暂停
    private var playState = 0
    
    private lazy var c_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = Color.clear
        control.alpha = 0.0
        return control
    }()
    
    lazy var back_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("返回_white")!)
        control.addTarget(self, action: #selector(close), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    lazy var delete_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("mycenter_icon_更多")!)
        control.addTarget(self, action: #selector(deleteAction), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    lazy var play_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("n_icon_全屏播放")!)
        control.isHidden = true
        return control
    }()
    
    
//  MARK:-
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Color.black
        playView.backgroundColor = Color.clear
        self.view.addSubview(playView)
        playView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalTo(self.view)
        }
        self.view.addSubview(c_navigation_bar)
        c_navigation_bar.snp.makeConstraints { (make) in
            make.top.right.left.equalTo(self.view)
            make.height.equalTo(statusBarHeight+navigationBarHeight)
        }
        c_navigation_bar.addSubview(back_btn)
        back_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(44)
            make.left.equalTo(self.c_navigation_bar).offset(8)
            
            make.top.equalTo(self.c_navigation_bar).offset(statusBarHeight)
        }
        if show_delete_action {
            c_navigation_bar.addSubview(delete_btn)
            
            delete_btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(44)
                make.right.equalTo(self.c_navigation_bar).offset(-15)
                make.centerY.equalTo(back_btn)
            }
        }
        
        
        self.view.addSubview(play_image_view)
        play_image_view.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
            make.width.height.equalTo(61)
        }
        
        let gez = UITapGestureRecognizer.init(target: self, action: #selector(play_view_handle))
        
        playView.addGestureRecognizer(gez)
        
        d_t_init_u_r_l()
        
        
    
    }
    
    func d_t_init_u_r_l(){
        
        if type == .localUrl {
            
            let localUrl = URL(fileURLWithPath: self.videoUrl)
            
            url = localUrl
            
//            url = URL.init(string: self.videoUrl) ?? URL(fileURLWithPath: self.videoUrl)
            
        }
        else if type == .networkUrl{
            
            if let videoURL = URL.init(string: self.videoUrl){
                 
                    url = videoURL
                
            }else{
                
                print("DTPlayerViewController error")
            }
        }
        else{
            
            if let exsitAsset  = self.asset,exsitAsset.mediaType == PHAssetMediaType.video{
                PHCachingImageManager().requestAVAsset(forVideo: exsitAsset, options: nil) { (asset, audioMix, info) in
                    
                    main_thread_execute {
                        
                        let urlAsset = asset as! AVURLAsset
                        
                        self.url = urlAsset.url
                    }
                }
            }
        }
    }

    
    func d_tinit_player(){
        
        if url == nil {
            return
        }
        
        let item = AVPlayerItem.init(url: url)
        
        let player = AVPlayer.init(playerItem: item)
        
        let playerLayer = AVPlayerLayer(player: player)
        
        playerLayer.videoGravity = .resizeAspect
        
        playerLayer.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        
        self.playLayer = playerLayer
        
        NotificationCenter.default.addObserver(self, selector: #selector(self.player_did_finish_playing(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
        
        self.playView.layer.addSublayer(playerLayer)
        self.player = player
        
//        self.player?.addObserver(self, forKeyPath: "status", options: [.new], context: &player_status_context)

//    upgrade swift4.2
        do{
            if #available(iOS 10.0, *) {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [])
                
            } else {
                
                // Fallback on earlier versions
                
            }
            
        }
        catch {
            // report for an error
            print("AVAudioSession AVAudioSessionCategoryPlayback")
        }
        
        play()
        
        
    }
    
    func play() {
        self.player?.play()
        playState = 0
        UIView.animate(withDuration: 0.25) {
            self.c_navigation_bar.alpha = 0.0
        }
        self.play_image_view.isHidden = true
    }
    
    func stop(){
        self.player?.pause()
        playState = 1
        UIView.animate(withDuration: 0.25) {
            self.c_navigation_bar.alpha = 1
        }
        self.play_image_view.isHidden = false
    }
    
    func remove_player_layer()  {
        self.playLayer?.removeFromSuperlayer()
        self.playLayer = nil
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func player_did_finish_playing(note: Notification) {
        
        //        print("播放完成")
        
        if let playerItem = note.object as? AVPlayerItem{
            
            if let currentItem = self.player?.currentItem,playerItem == currentItem{
                
//                print("DTPlayerViewController -- 两个Player 相同")
                
                playState = 1
                if let player = self.player{
                    player.seek(to: CMTime.zero)
                    player.play()
                    playState = 0
                }
                
                return
            }
        }
        
        
    }
    
    
//    MARK:- Event
    @objc func play_view_handle(){
        if playState == 0 {
            self.stop()
            
        }else{
            self.play()
            
        }
    }
    
    @objc func close(){
        self.stop()
        self.dismiss(animated: true) {
            self.remove_player_layer()
//            self.removeNotificationObserver(name: NSNotification.Name.AVPlayerItemDidPlayToEndTime)
        }
    }
    @objc func deleteAction(){
        
        
        if  let block = self.delete_block {
            block()
        }
//        self.stop()
//        self.remove_player_layer()
//        self.removeNotificationObserver(name: NSNotification.Name.AVPlayerItemDidPlayToEndTime)
        
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
    {

        //  Check status
        if keyPath == "status"
        {
            let status = change![.newKey] as! Int

            print("observeValue(forKeyPath keyPath ：status",status)
            //  Status is not unknown

        }
    
        
    }
}

